package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/model/response"
	"strconv"
)

func GetAchievement(id uint) (err error, achievement model.Achievement) {
	err = global.GVA_DB.Where("ID = ?", id).First(&achievement).Error
	return err, achievement
}

func CreateAchievement(achievement model.Achievement) (err error) {
	err = global.GVA_DB.Create(&achievement).Error
	return err
}
func DeleteAchievement(id uint) (err error) {
	err = global.GVA_DB.Where("ID = ?", id).Delete(&model.Achievement{}).Error
	return err
}

func UpdateAchievement(data model.Achievement) (err error) {
	err = global.GVA_DB.Updates(data).Where("id = ?", data.ID).Error
	return err
}

func GetAchievements(userid uint, pageSize int, pageNum int) (err error, list interface{}, total int) {
	var achievements []model.Achievement
	var tt int64

	err = global.GVA_DB.Limit(pageSize).Offset((pageNum-1)*pageSize).Where("user_id = ?", userid).Find(&achievements).Count(&tt).Error

	tmp := strconv.FormatInt(tt, 10)
	total, _ = strconv.Atoi(tmp)
	return err, achievements, total
}
func ChangeAchievementVisiblity(id uint) (err error) {
	var data model.Achievement
	global.GVA_DB.Where("id = ?", id).First(&data)
	err = global.GVA_DB.Model(&model.Achievement{}).Where("id = ? ", id).Update("is_visible", !data.IsVisible).Error
	return err
}

//获取今年该用户所有
func GetAllAchievementsByYear(id uint, year int) (error, interface{}, int64) {
	var data []model.Achievement
	var tt int64
	err := global.GVA_DB.Where("user_id = ? AND year = ?", id, year).Find(&data).Count(&tt).Error
	return err, data, tt
}

func GetAchievementsDynamic(info request.AchievementSearchInfo) (err error, list interface{}, total int64) {
	var achievements []response.AchievementResponse
	var userIds []uint
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.Achievement{}).Select("teacher.teacher_name as name, achievement.*").
		Joins("left join teacher on achievement.user_id = teacher.user_id")

	if info.AchievementName != "" {
		db = db.Where("achievement_name LIKE ?", "%"+info.AchievementName+"%")
	}

	if info.AchievementCategory != "" {
		db = db.Where("achievement_category = ?", info.AchievementCategory)
	}

	if info.AchievementLevel != "" {
		db = db.Where("achievement_level = ?", info.AchievementLevel)
	}

	if info.Year != "" {
		year, _ := strconv.Atoi(info.Year)
		db = db.Where("year = ?", year)
	}

	if info.Name != "" {
		userIds, err = model.GetUserIdsByTeacherName(info.Name)
		if len(userIds) != 0 {
			db = db.Where("teacher.user_id IN ?", userIds)

		}
	}

	err = db.Count(&total).Error
	if err != nil {
		return err, nil, 0
	}

	err = db.Limit(limit).Offset(offset).Find(&achievements).Error
	return err, achievements, total

}
